package net.oschina.ivansong.rpc.base.imp.consumer.test;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

import net.oschina.ivansong.rpc.base.demo.api.IUserService;

public class UserShowController {
 public static void main(String[] args) {
	 IUserService userService = (IUserService) getRemoteService(IUserService.class);
	 System.out.println("username:" + userService.getUserById(12).getName());
	 
 }
 private static Object getRemoteService(final Class<?> clazz) {
	 return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {

		@Override
		public Object invoke(Object object, Method method, Object[] params) throws Throwable {
			Socket socket = new Socket("127.0.0.1", 5666);
			OutputStream out = socket.getOutputStream();
			ObjectOutputStream outObj = new ObjectOutputStream(out);
			outObj.writeUTF(clazz.getName());
			outObj.writeUTF(method.getName());
			outObj.writeObject(method.getParameterTypes());
			outObj.writeObject(params);

			ObjectInputStream inObj = new ObjectInputStream(socket.getInputStream());
			Object res = inObj.readObject();
			
			outObj.close();
			out.close();
			inObj.close();
			socket.close();
			return res;
		}
		 
	 });
 }
}
